import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Tree, Switch, Tooltip } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, KeyOutlined, MenuOutlined, ToolOutlined, ApiOutlined } from '@ant-design/icons';
import AuthorizedButton from '@/components/Authorized/AuthorizedButton';
import { request } from 'umi';
import SearchForm from './SearchForm';
import moment from 'moment';

// 获取角色列表
const fetchRoles = async (params) => {
  return request('/api/v1/role', {
    method: 'GET',
    params,
  });
};

// 创建角色
const createRole = async (data) => {
  return request('/api/v1/role', {
    method: 'POST',
    data,
  });
};

// 更新角色
const updateRole = async (data) => {
  return request(`/api/v1/role/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 删除角色
const deleteRole = async (id) => {
  return request(`/api/v1/role/${id}`, {
    method: 'DELETE',
  });
};

// 获取权限列表
const fetchPermissions = async () => {
  return request('/api/v1/permission', {
    method: 'GET',
  });
};

// 获取角色权限
const fetchRolePermissions = async (roleId) => {
  return request(`/api/v1/role/${roleId}/permission`, {
    method: 'GET',
  });
};

// 分配角色权限
const assignRolePermissions = async (data) => {
  return request(`/api/v1/role/${data.roleId}/permission`, {
    method: 'POST',
    data,
  });
};

// 将权限列表转换为树形结构
const convertToTreeData = (permissions) => {
  // 找出所有顶级权限（parentId为0或null的）
  const rootPermissions = permissions.filter(p => !p.parent_id);
  
  // 递归构建树
  const buildTree = (parentPermissions) => {
    return parentPermissions.map(parent => {
      // 找出所有以当前权限为父级的子权限
      const children = permissions.filter(p => p.parent_id === parent.id);
      
      // 根据权限类型设置不同的样式和图标
      const nodeType = parent.type || 'api';
      
      return {
        title: parent.name,
        key: parent.id.toString(),
        children: children.length > 0 ? buildTree(children) : [],
        // 添加额外属性用于自定义渲染
        type: nodeType,
        module: parent.module,
        description: parent.description,
        identifier: parent.identifier,
        nodeData: parent, // 保存完整的权限数据
      };
    });
  };
  
  return buildTree(rootPermissions);
};

const RoleList = () => {
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [permissionModalVisible, setPermissionModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加角色');
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [currentRole, setCurrentRole] = useState(null);
  const [permissions, setPermissions] = useState([]);
  const [permissionTree, setPermissionTree] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });

  // 搜索参数
  const [searchParams, setSearchParams] = useState({});

  // 获取角色列表
  const fetchRoleList = async () => {
    try {
      setLoading(true);
      const res = await fetchRoles({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setRoles(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取角色列表失败');
      }
    } catch (error) {
      console.error('获取角色列表出错:', error);
      message.error('获取角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取所有权限
  const fetchAllPermissions = async () => {
    try {
      const res = await fetchPermissions();
      if (res.success) {
        setPermissions(res.data || []);
        setPermissionTree(convertToTreeData(res.data || []));
      } else {
        message.error(res.message || '获取权限列表失败');
      }
    } catch (error) {
      console.error('获取权限列表出错:', error);
      message.error('获取权限列表失败');
    }
  };

  useEffect(() => {
    fetchRoleList();
    fetchAllPermissions();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 1 ? '#52c41a' : '#ff4d4f' }}>
          {status === 1 ? '正常' : '禁用'}
        </span>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <AuthorizedButton 
            permission="role:update"
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </AuthorizedButton>
          <AuthorizedButton 
            permission="role:permission"
            type="primary" 
            icon={<KeyOutlined />} 
            size="small"
            onClick={() => handlePermission(record)}
          >
            权限
          </AuthorizedButton>
          <Popconfirm
            title="确定要删除此角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AuthorizedButton 
              permission="role:delete"
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </AuthorizedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理添加角色
  const handleAdd = () => {
    setModalTitle('添加角色');
    setEditingId(null);
    form.resetFields();
    form.setFieldsValue({ status: 1 }); // 默认状态为正常
    setModalVisible(true);
  };

  // 处理编辑角色
  const handleEdit = (record) => {
    setModalTitle('编辑角色');
    setEditingId(record.id);
    form.setFieldsValue({
      name: record.name,
      description: record.description,
      status: record.status,
    });
    setModalVisible(true);
  };

  // 处理角色权限
  const handlePermission = async (record) => {
    setCurrentRole(record);
    try {
      const res = await fetchRolePermissions(record.id);
      if (res.success) {
        // 将权限ID转换为字符串
        const permissionIds = (res.data || []).map(id => id.toString());
        setCheckedKeys(permissionIds);
        setPermissionModalVisible(true);
      } else {
        message.error(res.message || '获取角色权限失败');
      }
    } catch (error) {
      console.error('获取角色权限出错:', error);
      message.error('获取角色权限失败');
    }
  };

  // 处理删除角色
  const handleDelete = async (id) => {
    try {
      const res = await deleteRole(id);
      if (res.success) {
        message.success('删除成功');
        fetchRoleList();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除角色出错:', error);
      message.error('删除失败');
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingId) {
        // 更新角色
        const res = await updateRole({
          id: editingId,
          ...values,
        });
        if (res.success) {
          message.success('更新成功');
          setModalVisible(false);
          fetchRoleList();
        } else {
          message.error(res.message || '更新失败');
        }
      } else {
        // 创建角色
        const res = await createRole(values);
        if (res.success) {
          message.success('创建成功');
          setModalVisible(false);
          fetchRoleList();
        } else {
          message.error(res.message || '创建失败');
        }
      }
    } catch (error) {
      console.error('提交表单出错:', error);
    }
  };

  // 处理权限分配
  const handleAssignPermission = async () => {
    if (!currentRole) return;
    
    try {
      const res = await assignRolePermissions({
        roleId: currentRole.id,
        permissions: checkedKeys.map(key => parseInt(key)),
      });
      
      if (res.success) {
        message.success('权限分配成功');
        setPermissionModalVisible(false);
      } else {
        message.error(res.message || '权限分配失败');
      }
    } catch (error) {
      console.error('分配权限出错:', error);
      message.error('权限分配失败');
    }
  };

  // 处理权限树选择变化
  const onCheckPermission = (checkedKeysValue) => {
    setCheckedKeys(checkedKeysValue);
  };

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setPagination({
      ...pagination,
    });
  };

  // 处理搜索
  const handleSearch = (values) => {
    setSearchParams(values);
    setPagination({
      ...pagination,
      current: 1, // 搜索时重置为第一页
    });
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1, // 重置搜索时重置为第一页
    });
  };

  return (
    <PageContainer>
      <Card
        title="角色管理"
        extra={
          <AuthorizedButton 
            permission="role:create"
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加角色
          </AuthorizedButton>
        }
      >
        <SearchForm onSearch={handleSearch} onReset={handleResetSearch} />
        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </Card>

      {/* 添加/编辑角色弹窗 */}
      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="角色描述"
          >
            <Input.TextArea placeholder="请输入角色描述" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value={1}>正常</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 分配权限弹窗 */}
      <Modal
        title={`分配权限: ${currentRole?.name || ''}`}
        visible={permissionModalVisible}
        onOk={handleAssignPermission}
        onCancel={() => setPermissionModalVisible(false)}
        width={600}
      >
        {/* 权限类型图例说明 */}
        <div style={{ marginBottom: 16 }}>
          <Space>
            <span><b>图例说明：</b></span>
            <span style={{ fontWeight: 'bold' }}>菜单权限</span>
            <span style={{ color: '#1890ff' }}>按钮权限</span>
            <span style={{ color: '#52c41a' }}>接口权限</span>
          </Space>
        </div>
        <Tree
          checkable
          checkedKeys={checkedKeys}
          onCheck={onCheckPermission}
          treeData={permissionTree}
          titleRender={(nodeData) => {
            const { title, type, module, description, identifier } = nodeData;
            
            // 根据权限类型设置不同的样式
            let titleStyle = {};
            let icon = null;
            
            if (type === 'menu') {
              titleStyle = { fontWeight: 'bold' };
              icon = <MenuOutlined style={{ marginRight: 4 }} />;
            } else if (type === 'button') {
              titleStyle = { color: '#1890ff' };
              icon = <ToolOutlined style={{ marginRight: 4 }} />;
            } else if (type === 'api') {
              titleStyle = { color: '#52c41a' };
              icon = <ApiOutlined style={{ marginRight: 4 }} />;
            }
            
            return (
              <Tooltip title={`${description || ''}${description ? '\n' : ''}标识符: ${identifier || '-'}`}>
                <span>
                  {icon}
                  <span style={titleStyle}>{title}</span>
                  {module && <span style={{ color: '#999', marginLeft: 8 }}>[{module}]</span>}
                </span>
              </Tooltip>
            );
          }}
        />
      </Modal>
    </PageContainer>
  );
};

export default RoleList;